package app.widget;

import java.util.Calendar;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.LinearLayout.LayoutParams;
import app.utils.Tools;

import com.longevityassistant.activity.R;

/**
 * 单元格控键
 * @author EX-XIAOFANQING001
 * @version [Android PABank C01, 2011-12-28]
 */
public class DateCell extends View {

	public final static int ANIM_ALPHA_DURATION = 50;
	
	// fields
	private final static float mTextSize = 16;
	private final static int iMargin = 1;
	
	// 如果不是当前月的透明度
	private final static int mAlphaInactiveMonth = 0x55;

	// fields
	private int mYear = 0;
	private int mMonth = 0;
	private int mDay = 0;

	// fields
	private OnItemClick itemClick = null;
	
	private Paint mPaint = new Paint();
	
	private RectF mBounds = new RectF();
	
	//
	private String mDate = "";

	// fields
	private boolean mIsSelected = false;
	
	private boolean mIsActiveMonth = false;
	
	private boolean mIsToday = false;
	
//	private boolean mIsHoliday = false;
	
	private boolean mIsTouchedDown = false;
	
	
	private int mTextColor;

	public DateCell(Context context, int width, int height) {
		super(context);
		setFocusable(true);
		setLayoutParams(new LayoutParams(width, height));
		
		setBackgroundResource(R.drawable.app_widget_calendar2_bg_cellbox);
		mTextColor = getResources().getColor(R.color.col_pa04);
	}

	/**
	 * 设置该单元格的日期
	 * @param year 当前的年份
	 * @param month 当前的月份
	 * @param day 当前的天数
	 * @param isToday 是否是今天
	 * @param isWeekEnd 是否是周末
	 * @param activeMonth 是否是当前月的日
	 * @param hasIncome 是否有收入
	 * @param hasOutlay 是否有支出  
	 */
	public void setDate(
	        int year, 
	        int month, 
	        int day, 
	        boolean isToday, 
	        boolean isWeekEnd, 
	        int activeMonth, 
	        boolean hasIncome, 
	        boolean hasOutlay, 
	        boolean hasOtherEvent) {
	    
		mYear = year;
		mMonth = month;
		mDay = day;

		this.mDate = Integer.toString(mDay);
		this.mIsActiveMonth = (mMonth == activeMonth);
		this.mIsToday = isToday;
//		this.mIsHoliday = isWeekEnd;
		
		this.hasIncome = hasIncome;
		this.hasOutlay = hasOutlay;
		this.hasOtherEvent = hasOtherEvent;
	}
	
	public boolean getSelected() {
        return this.mIsSelected;
    }

    @Override
    public void setSelected(boolean bEnable) {
        if (this.mIsSelected != bEnable) {
            this.mIsSelected = bEnable;
            this.invalidate();
        }
    }

	public void setItemClick(OnItemClick itemClick) {
		this.itemClick = itemClick;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean result = super.onKeyDown(keyCode, event);
		if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) || (keyCode == KeyEvent.KEYCODE_ENTER)) {
			doItemClick();
		}
		return result;
	}

	public void doItemClick() {
		if (itemClick != null) {
			itemClick.OnClick(this);
		}
	}

	@Override
	protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
		super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
		invalidate();
	}

	public Calendar getDate() {
		Calendar date = Calendar.getInstance();
		date.clear();
		
		date.set(Calendar.YEAR, mYear);
		date.set(Calendar.MONTH, mMonth);
		date.set(Calendar.DAY_OF_MONTH, mDay);
		
		return date;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		// init rectangles
		mBounds.set(0, 0, this.getWidth(), this.getHeight());

		// drawing
		boolean isFocused = isViewFocused();

		drawDayView(canvas, isFocused);
		
		drawDayNumber(canvas, isFocused);
		
		drawImg(canvas);
	}
	
	private boolean hasIncome = true;
	private boolean hasOutlay = true;
	private boolean hasOtherEvent ;
	
	
	private static final int ICON_SIZE = 12;
	
	/**
	 * 根据事件状态绘制小圆点
	 * 总共包括3种状态:
	 * 1.收入  2.支出  3.其它事件
	 * 收入绘制红点,支出绘绿点, 其它事件绘黄点
	 * 
	 * @param canvas
	 */
	private void drawImg(Canvas canvas) {
	    canvas.save();
	    
	    int imgCount = 0;
	    
	    if (hasIncome) {
	        imgCount ++;
	    }
	    
	    if (hasOutlay) {
	        imgCount ++;
	    }
	    
	    if (hasOtherEvent) {
	        imgCount ++;
	    }
	    
	   
	    
	    if (imgCount == 0) {
	        return ;
	    }
	    
	    Log.i("zbkc", "imgCount:" + imgCount + hasIncome + hasOutlay + hasOtherEvent);
	    
	    // 垂直圆点的y坐标
	    int  posY = Tools.getActualSize(getContext(), 22) ;
	    
	    if (imgCount == 1) { // 一个点画中间
	        int pos1X = getWidth() / 2 - Tools.getActualSize(getContext(), ICON_SIZE) / 2;
	        int drawableRes = R.drawable.app_widget_ca_yellow_img;
	        
	        if (hasIncome) {
	            drawableRes = R.drawable.app_widget_ca_red_img;
	        }

	        if (hasOutlay) {
	            drawableRes = R.drawable.app_widget_ca_green_img;
	        }
	        
	        if (hasOtherEvent) {
	            drawableRes = R.drawable.app_widget_ca_yellow_img;
	        }
	        
	        drawImgIcon(canvas, pos1X, posY, drawableRes);
	        canvas.restore();
	        return ;
	    }
	    
	    if (imgCount == 2) { // 两个点对半分
	        int distance = 4;
	        int pos1X = getWidth() / 2 - (Tools.getActualSize(getContext(), ICON_SIZE) + distance);
	        int pos2X = getWidth() / 2 + distance;
	        
	        int res1 = 0;
	        int res2 = 0;
	        if (hasIncome && hasOutlay) {
	            res1 = R.drawable.app_widget_ca_red_img;
	            res2 = R.drawable.app_widget_ca_green_img;
	        }
	        
	        if (hasIncome && hasOtherEvent) {
	            res1 = R.drawable.app_widget_ca_red_img;
	            res2 = R.drawable.app_widget_ca_yellow_img;
	        }
	        
	        if (hasOutlay && hasOtherEvent) {
	            res1 = R.drawable.app_widget_ca_green_img;
	            res2 = R.drawable.app_widget_ca_yellow_img;
	        }
	        
	        drawImgIcon(canvas, pos1X, posY, res1);
            drawImgIcon(canvas, pos2X, posY, res2);
	        
	        canvas.restore();
	        
	        return ;
	    }
	    
	    if (imgCount == 3) { // 三个点均分
	       
	        int distance = 6;
	        int pos1X = getWidth() / 2 - (Tools.getActualSize(getContext(), ICON_SIZE) + distance);
	        int pos2X = getWidth() / 2 - Tools.getActualSize(getContext(), ICON_SIZE) / 2;
            int pos3X = getWidth() / 2 + distance;
            
            drawImgIcon(canvas, pos1X, posY, R.drawable.app_widget_ca_red_img);
            drawImgIcon(canvas, pos2X, posY, R.drawable.app_widget_ca_yellow_img);
            drawImgIcon(canvas, pos3X, posY, R.drawable.app_widget_ca_green_img);
            
            canvas.restore();
            
	        return ;
	    }
	    
//	    if (hasIncome) {
//	        int textPosX = Tools.getActualSize(getContext(), 8); 
//	        int textPosY = Tools.getActualSize(getContext(), 23) ;
//	        drawImgIcon(canvas, textPosX, textPosY, getResources().getDrawable(R.drawable.kal_marker));
//	    }
//	    
//	    if (hasOutlay) {
//	        int textPosX = Tools.getActualSize(getContext(), 25); 
//            int textPosY = Tools.getActualSize(getContext(), 23);
//            drawImgIcon(canvas, textPosX, textPosY, getResources().getDrawable(R.drawable.kal_collect));
//	    }
        
	}
	
	
	private void drawImgIcon(Canvas canvas, int x, int y, int img) {
        BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(img);
        drawable.setBounds(x, y, x + Tools.getActualSize(getContext(), ICON_SIZE),  y + Tools.getActualSize(getContext(), ICON_SIZE));
        drawable.draw(canvas);
	}

	/**
	 * 绘制单元格的背景 
	 * @param canvas
	 * @param isFocused
	 */
	private void drawDayView(Canvas canvas, boolean isFocused) {
	    
		if (isFocused) {
            
            BitmapDrawable background = null;
            if (mIsActiveMonth) {
                Log.i("zbkc", "mIsActiveMonth");
                background =  new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.app_widget_calendar2_cellbox_today_h));
            } else {
                Log.i("zbkc", "!mIsActiveMonth");
                background =  new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.app_widget_calendar2_cellbox_unable));
            }
            background.setBounds((int)mBounds.left, (int)mBounds.top, (int)mBounds.right, (int)mBounds.bottom);
            background.draw(canvas);
		}
		
		if (mIsToday) {
		    BitmapDrawable background = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.app_widget_calendar2_cellbox_today));
		    background.setBounds((int)mBounds.left, (int)mBounds.top, (int)mBounds.right, (int)mBounds.bottom);
		    background.draw(canvas);
		}
		
		if (mIsSelected) {
		    BitmapDrawable background = null;
		    if (mIsActiveMonth) {
		        Log.i("zbkc", "mIsActiveMonth");
		        background =  new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.app_widget_calendar2_cellbox_today_h));
		    } else {
		        Log.i("zbkc", "!mIsActiveMonth");
		        background =  new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.app_widget_calendar2_cellbox_unable));
		    }
		    background.setBounds((int)mBounds.left, (int)mBounds.top, (int)mBounds.right, (int)mBounds.bottom);
		    background.draw(canvas);
		}
		
	
	}

	public void drawDayNumber(Canvas canvas, boolean isFocused) {
	    
		// draw day number
		mPaint.setTypeface(null);
		mPaint.setAntiAlias(true);
		mPaint.setShader(null);
//		mPaint.setFakeBoldText(true);
		mPaint.setTextSize(Tools.getActualSize(getContext(), (int)mTextSize));

		mPaint.setUnderlineText(false);
		
		
		int textPosX = (int) mBounds.right - (int) mPaint.measureText(mDate);
		int textPosY = (int) mBounds.bottom + (int) (-mPaint.ascent())	- getTextHeight() - 7;

		textPosX -= ((int) mBounds.width() >> 1) - ((int) mPaint.measureText(mDate) >> 1);
		textPosY -= ((int) mBounds.height() >> 1) - (getTextHeight() >> 1);

		// draw text
		if (mIsSelected || isFocused) {
			
		    if (mIsSelected) {
				mPaint.setColor(Color.WHITE);
			}
			
			if (isFocused) {
				mPaint.setColor(Color.WHITE);
			}
			
		} else {
			mPaint.setColor(mTextColor); 
		}

		if (!mIsActiveMonth) {
			mPaint.setAlpha(mAlphaInactiveMonth);
		}
		
		if (mIsToday) {
//            mPaint.setUnderlineText(true);
            mPaint.setColor(Color.WHITE);
        }

		canvas.drawText(mDate, textPosX, textPosY + iMargin, mPaint);

	}
	
	private int getTextHeight() {
	    return (int) (- mPaint.ascent() + mPaint.descent());
	}

	public boolean isViewFocused() {
		return (this.isFocused() || mIsTouchedDown);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		boolean bHandled = false;
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			bHandled = true;
			mIsTouchedDown = true;
			invalidate();
			startAlphaAnimIn(DateCell.this);
		}
		if (event.getAction() == MotionEvent.ACTION_CANCEL) {
			bHandled = true;
			mIsTouchedDown = false;
			invalidate();
		}
		if (event.getAction() == MotionEvent.ACTION_UP) {
			bHandled = true;
			mIsTouchedDown = false;
			invalidate();
			if (mIsActiveMonth) {
			    doItemClick();
			}
		}
		return bHandled;
	}

	private static void startAlphaAnimIn(View view) {
		AlphaAnimation anim = new AlphaAnimation(0.5F, 1);
		anim.setDuration(ANIM_ALPHA_DURATION);
		anim.startNow();
		view.startAnimation(anim);
	}
	
	/**
	 * 单元格点击事件监听器
	 * [一句话功能简述]<BR>
	 * [功能详细描述]
	 * @author EX-XIAOFANQING001
	 * @version [Android PABank C01, 2011-12-28]
	 */
    public interface OnItemClick {
        public void OnClick(DateCell item);
    }

}
